package com.briup.prs;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.KeyValueTextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Step3 extends Configured implements Tool {
    public static class Step3Mapper extends Mapper<Text, Text, Text, Text> {
        @Override
        /**
         * key=userId:shopId
         * value=偏好值
         *
         * key2=userId
         * value2=shopId
         */
        protected void map(Text key, Text value, Context context) throws IOException, InterruptedException {
            String[] userAndShop = key.toString().split(":");
            context.write(new Text(userAndShop[0]), new Text(userAndShop[1]));

        }
    }

    public static class Step3Reducer extends Reducer<Text, Text, Text, Text> {
        @Override
        /**
         * key: userId
         * values: [shopId,shopId,shopId,……]
         */
        protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
            List<String> list = new ArrayList<>();
            for (Text value : values) {
//                将商品id放到集合中去
                list.add(value.toString());
            }
//控制商品列表做笛卡尔积
            for (int i = 0; i < list.size(); i++) {
                for (int j = 0; j < list.size(); j++) {
//                    商品自己和自己共现  数据无意义
                    if (i == j) {
                        continue;
                    }
                   context.write(new Text(list.get(i)),new Text(list.get(j)));

                }

            }

        }
    }

    @Override
    public int run(String[] args) throws Exception {
        Configuration conf = getConf();
        String in = conf.get("in");
        String out = conf.get("out");
        Job job = Job.getInstance(conf);
        job.setJobName("step3");
        job.setJarByClass(this.getClass());

        job.setInputFormatClass(KeyValueTextInputFormat.class);
        KeyValueTextInputFormat.addInputPath(job,new Path(in));

        job.setMapperClass(Step3Mapper.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(Text.class);

        job.setReducerClass(Step3Reducer.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);

        TextOutputFormat.setOutputPath(job,new Path(out));
        return job.waitForCompletion(true)?0:-1;
    }

    public static void main(String[] args) throws Exception {
        ToolRunner.run(new Step3(), args);
    }
}
